function [ output ] = Analyze()
%ANALYZE Processes EVERYTHING!
diary on

subjects = GetSubjects();
peaks = load('PeaksDB');
electrodes = GetElectrodes();

N1WindowCfg = [-15 15];
N2WindowCfg = [-15 15];
P1WindowCfg = [-15 15];
P2WindowCfg = [-20 20];

output.subjects = subjects;
% C = false;
for i=1:length(subjects)
    disp(['==================> ' subjects(i).Name]);
%     if C; continue; end;
    tStart = tic;

    % Haal de juiste gegevens uit de database
    [N1 N2 P1 P2] = RetrievePeakInfo(peaks.peaksDB, subjects(i));
    % create peak window variables
    N1W = N1 + N1WindowCfg;
    N2W = N2 + N2WindowCfg;
    P1W = P1 + P1WindowCfg;
    P2W = P2 + P2WindowCfg;

    % for loop over blocks en periods
    for b=1:3
        for p=1:4
            disp(['Block ' num2str(b) ' Period ' num2str(p) '...']);
            % load EEG data (.mat file)
            if isempty(subjects(i).EpochData{b,p})
                disp('No file available, skipping...');
                continue;
            end
            data = load(['EEG Data\' subjects(i).EpochData{b,p}]);

            results = [];


            % Extract peak info per electrode
            for e=1:length(electrodes)
                if isempty(find(strcmp(electrodes{e},fieldnames(data)), 1))
                    warning(['Electrode ''' electrodes{e} ''' not available in data...']);
                    continue;
                end
                disp(['Electrode ' num2str(e) '/' num2str(length(electrodes)) ': ' electrodes{e}]);
                results.(electrodes{e}).N1 = [];
                results.(electrodes{e}).P1 = [];
                results.(electrodes{e}).N2 = [];
                results.(electrodes{e}).P2 = [];


                % loop over rows (trials)
                for t=1:size(data.(electrodes{e}), 1)
                    trialdata = data.(electrodes{e})(t,:);

                    % Bereken peaks
                    warning off;
                    results.(electrodes{e}).trial(t).N1 = FindThePeak(trialdata, data.t, N1W, false);
                    results.(electrodes{e}).trial(t).P1 = FindThePeak(trialdata, data.t, P1W, true);
                    results.(electrodes{e}).trial(t).N2 = FindThePeak(trialdata, data.t, N2W, false);
                    results.(electrodes{e}).trial(t).P2 = FindThePeak(trialdata, data.t, P2W, true);
                    warning on;

                end
            end
            % Sla berekende data op
            filename = ['P:\PeakAnalysis\Results\' subjects(i).Name ' - Period ' num2str(p) ' Block ' num2str(b) '.mat'];
            save(filename, '-v7.3', 'results');
            output.results(i).times = data.t;
            output.results(i).period{p}.block{b} = filename;
            tStop = toc(tStart);
            disp(['Results in ' num2str(tStop) 's']);
        end
    end
end
save('P:\PeakAnalysis\output.mat', '-v7.3', 'output');
diary off

end
